package com.codeplex.boomships.Server;

import java.rmi.Naming;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.util.ArrayList;
import java.util.List;
import java.rmi.server.UnicastRemoteObject;

import com.codeplex.boomships.Common.*;
import com.codeplex.boomships.communication.*;
import com.codeplex.boomships.Persistence.*;

public class ServerImpl extends UnicastRemoteObject implements Server{
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	private String name;
	private List<Observer> lstClients;
	private List<ServerThread> lstServers;
	
	public ServerImpl(String pName) throws RemoteException{
		super();
		this.lstClients = new ArrayList<Observer>();
		this.name = pName;
	}
	
	public synchronized Msg<String> login(Player pPlayer) throws RemoteException{
		Msg<String> ret = new Msg<String>();
		ret.setSender(Constants.SERVER_NAME);
		Player p = PersistenceManager.getInstance().getPlayer(pPlayer);
		if(p != null){
			ret.setCommand(Command.LOGIN_SUCCESSFUL);
			ret.setParam("Bienvenido a BoomShips, " + p.getUsername());
		}else{
			ret.setCommand(Command.LOGIN_FAILED);
			ret.setParam("El nombre de usuario y/o password, son erroneos!");
		}
		return ret;
	}
	
	public synchronized Msg<String> register(Player pPlayer) throws RemoteException{
		Msg<String> ret = new Msg<String>();
		ret.setSender(Constants.SERVER_NAME);
		if( PersistenceManager.getInstance().insertPlayer(pPlayer)){
			ret.setCommand(Command.REGISTER_SUCCESSFUL);
			ret.setParam("Se ha registrado con exito!, bienvenido a BoomShip!");
		}else{
			ret.setCommand(Command.REGISTER_FAILED);
			ret.setParam("No se ha podido llevar a cabo el registro, intente con otro nombre de usuario");
		}
		return ret;
	}
	
	public static void main(String[] args){
		try{
			System.setProperty("java.security.policy", Constants.JAVAPOLICY_LOCATION);
			LocateRegistry.createRegistry(1099);
			Naming.rebind("//localhost/Server", new ServerImpl(Constants.SERVER_NAME));
			System.out.println("Servidor corriendo!");
		}catch (Exception e){
			System.err.println("Server exception: " + e.toString());
		}
	}
	
}
